#!/usr/bin/env python

# Copyright (c) 2009, Purdue University
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
# 
# Neither the name of the Purdue University nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""list zones and zone view assignments for roster"""


__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '0.15'


import os
import sys
import getpass

from optparse import OptionParser

from roster_user_tools import cli_common_lib
from roster_user_tools import roster_client_lib
from roster_user_tools.action_flags import List
from roster_user_tools.data_flags import Zone


class Args(List, Zone):
  pass


def main(args):
  """Collects command line arguments.

  Inputs:
    args: list of arguments from the command line
  """
  command = None
  if( args and not args[0].startswith('-') ):
    command = args.pop(0)
  usage = ('\n'
           '\n'
           'To list all zones:\n'
           '\t%s all\n'
           '\n'
           'To list forward zones:\n'
           '\t%s forward [-z <zone-name>] [-v <view-name>] [-0 <options>]\n'
           '\t[--origin <origin>] [-t <type>] [--cidr-block <cidr-block>]\n'
           '\n'
           'To list reverse zones:\n'
           '\t%s reverse [-z <zone-name>] [-v <view-name>] [-0 <options>]\n'
           '\t[--origin <origin>] [-t <type>] [--cidr-block <cidr-block>]\n'
           '\n' % tuple([sys.argv[0] for x in range(3)]))
  args_instance = Args(command, ['forward', 'reverse', 'all'], args, usage)
  options = args_instance.options

  try:
    cli_common_lib_instance = cli_common_lib.CliCommonLib(options)
  except cli_common_lib.ArgumentError, e:
    print 'ERROR: %s' % e
    sys.exit(1)

  if( options.origin and not options.origin.endswith('.') ):
    cli_common_lib.DnsError('Zone origin must terminate with "."', 1)

  views = roster_client_lib.RunFunction(
      u'ListViews', options.username,
      credfile=options.credfile, credstring=options.credstring,
      server_name=options.server, kwargs={
          u'view_name': options.view_name})['core_return']

  if( options.view_name and not views and options.view_name != 'any' ):
    cli_common_lib.DnsError('View not found.', 1)

  zones = roster_client_lib.RunFunction(
      u'ListZones', options.username,
      credfile=options.credfile, credstring=options.credstring,
      server_name=options.server, kwargs={
          u'zone_name': options.zone_name, u'zone_type': options.type,
          u'zone_origin': options.origin, u'view_name': options.view_name})[
              'core_return']

  reverse_range_zone_assignments = roster_client_lib.RunFunction(
      u'ListReverseRangeZoneAssignments', options.username,
      credfile=options.credfile, credstring=options.credstring,
      server_name=options.server, kwargs={
          u'zone_name': options.zone_name,
          u'cidr_block': options.cidr_block})['core_return']

  if( not options.no_header ):
    print_list = [['zone_name', 'view_name', 'zone_type', 'zone_origin',
                   'zone_options', 'cidr_block']]

  if( command == 'reverse' ):
    if( not reverse_range_zone_assignments ):
      cli_common_lib.DnsError('No zones found.', 1)
    for zone in reverse_range_zone_assignments:
      for view in zones[zone]:
        if( zones[zone][view]['zone_options'] == '' ):
          zone_options = ''
        else:
          zone_options = repr(zones[zone][view]['zone_options'])
        print_list.append([zone, view, zones[zone][view]['zone_type'],
                           zones[zone][view]['zone_origin'], zone_options,
                           reverse_range_zone_assignments[zone]])

  elif( command == 'forward' ):
    if( not zones ):
      cli_common_lib.DnsError('No zones found.', 1)
    for zone in zones:
      for view in zones[zone]:
        if( zone in reverse_range_zone_assignments ):
          continue
        if( zones[zone][view]['zone_options'] == '' ):
          zone_options = ''
        else:
          zone_options = repr(zones[zone][view]['zone_options'])
        print_list.append([zone, view, zones[zone][view]['zone_type'],
                           zones[zone][view]['zone_origin'],
                           zone_options, '-'])

  elif( command == 'all' ):
    for zone in zones:
      for view in zones[zone]:
        if( zone in reverse_range_zone_assignments ):
          cidr = reverse_range_zone_assignments[zone]
        else:
          cidr = '-'
        if( zones[zone][view]['zone_options'] == '' ):
          zone_options = ''
        else:
          zone_options = repr(zones[zone][view]['zone_options'])
        print_list.append([zone, view, zones[zone][view]['zone_type'],
                           zones[zone][view]['zone_origin'],
                           zone_options, cidr])
    
  print cli_common_lib_instance.PrintColumns(print_list,
                                    first_line_header=(not options.no_header))

if __name__ == "__main__":
  main(sys.argv[1:])
